package pers.xiaojun.boot.excel.convert;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.idev.excel.converters.Converter;
import cn.idev.excel.metadata.GlobalConfiguration;
import cn.idev.excel.metadata.data.ReadCellData;
import cn.idev.excel.metadata.data.WriteCellData;
import cn.idev.excel.metadata.property.ExcelContentProperty;
import pers.xiaojun.boot.common.util.DictUtils;
import pers.xiaojun.boot.excel.annotation.DictType;

/**
 * 字典转换器
 *
 * @author xiaojun
 * @since 2025-11-08
 */
public class DictConvert implements Converter<Object> {

    /**
     * Java类型值 -> Excel值
     *
     * @param value               字段值
     * @param contentProperty     字段信息
     * @param globalConfiguration 全局配置
     * @return Excel值
     * @throws Exception 异常
     */
    @Override
    public WriteCellData<String> convertToExcelData(Object value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String dictType = getDictType(contentProperty);
        if (StrUtil.isBlank(dictType) || value == null) {
            return new WriteCellData<>("");
        }
        String label = DictUtils.getDictLabel(dictType, String.valueOf(value));
        return new WriteCellData<>(label == null ? "" : label);
    }

    /**
     * Excel值 -> Java类型值
     *
     * @param cellData            Excel值
     * @param contentProperty     字段信息
     * @param globalConfiguration 全局配置
     * @return Java类型值
     * @throws Exception 异常
     */
    @Override
    public Object convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String dictType = getDictType(contentProperty);
        String label = cellData.getStringValue();
        if (StrUtil.isBlank(dictType) || StrUtil.isEmpty(label)) {
            return null;
        }
        String value = DictUtils.getDictValue(dictType, label);
        if (StrUtil.isBlank(value)) {
            return null;
        }
        return Convert.convert(contentProperty.getField().getType(), value);
    }

    /**
     * 获取字段注解 DictType 中的字典类型
     *
     * @param contentProperty 字段信息
     * @return 字典类型
     */
    private String getDictType(ExcelContentProperty contentProperty) {
        return contentProperty.getField().getAnnotation(DictType.class).value();
    }
}
